import os, re, urllib2, ftplib, tempfile, atexit, gzip

def removeTempFile(filename) :
	try : os.unlink(filename)
	except OSError : pass


class PDBDataConnector :
	'''Parent class for to define data connector interface. Data connector obtains info about basic categories in mmcif, ligcif and datacif for an entry.'''
	def __init__(s) : pass
	def makeFileObject(s, resourcestr) :
		'''make a file object from a filepath or URL. takes care of gzipped files too if path ends in .gz'''
		if re.compile("http.*://").search(resourcestr) :
			tempfd, tempfn = tempfile.mkstemp(prefix="tempfilePDBOI") ; os.close(tempfd) ; atexit.register(removeTempFile, tempfn)
			ofp = open(tempfn, 'w')
			for l in urllib2.urlopen(resourcestr) : ofp.write(l)
			ofp.close()
			fp = open(tempfn,'r')
		elif re.compile("ftp.*://").search(resourcestr) : raise NotImplementedError("FTP resources are not supported yet (%s)." % resourcestr)
		else : fp = open(resourcestr, 'r')
		if re.compile("\.gz *$").search(resourcestr) : fp = gzip.GzipFile(fileobj=fp)
		return fp
	def makeTempFile(s, resourcestr) :
		fp = s.makeFileObject(resourcestr)
		tempfd,tempfn = tempfile.mkstemp(prefix="tempfilePDBOI") ; os.close(tempfd) ; atexit.register(removeTempFile, tempfn)
		ofp = open(tempfn,'w')
		for l in fp : ofp.write(l)
		ofp.close()
		fp.close()
		return tempfn
	def getCategory(s, cat, item=None, mode="normal") :
		'''In "normal" mode:
				if item is None, a map containing all items and their values is returned, else only item's value is returned.
				in case this is a looped category, an iterator is returned similarly.
			In "iter" mode, an iterator is returned even when there is just 1 value.
			In "first" mode, only first hit is returned.
		'''
		raise NotImplementedError
